const db = require('../db/index');
require('dotenv').config({ path: '.env' })


//发布商品
exports.addGoods = (req, res) => {

    const goodsInfo = {
        ...req.body,
        release_time: new Date(),
        seller: req.user.nickname || req.user.username,
        seller_id: req.user.user_id
    }

    const sql = `INSERT into goods set ?;`;
    db.query(sql, goodsInfo, (err, results) => {
        //执行SQL语句失败
        if (err) return res.cc(err);
        //执行SQL语句成功，但是获取到的数据条数不等于1
        if (results.affectedRows !== 1) return res.cc('发布商品失败！');

        res.cc("发布商品成功！", 0)
    })
}

//查询未出售商品
exports.getGoods = (req,res)=>{
    const sql =`select * from goods where is_sell = 0;`;
    db.query(sql, (err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取商品列表失败！');

        res.send({
            status: 0,
            mesage: "获取商品列表成功!",
            retdata: results
        })
    })
}


//更新商品信息
exports.updateGoods = (req, res) => {
    const sql = `UPDATE goods SET ? WHERE goods_id = ?;`
    db.query(sql, [req.body, req.body.goods_id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('修改商品信息失败！')

        res.cc('修改商品信息成功!', 0)
    })
}

//删除商品
exports.deleteGoods = (req, res) => {
    const sql = `DELETE FROM goods WHERE goods_id = ?;`
    db.query(sql, req.body.goods_id, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('删除商品失败！')

        res.cc('删除商品成功!', 0)
    })
}

//查询出售的物品
exports.getMySellGoods = (req,res)=>{
    const sql =`select * from goods where seller_id = ?;`;
    db.query(sql, req.body.seller_id ,(err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取用户出售商品失败！');

        res.send({
            status: 0,
            mesage: "获取用户出售商品成功!",
            retdata: results
        })
    })
}

//查询我购买的商品
exports.getMyPayGoods = (req,res)=>{
    const sql =`select * from goods where purchaser_id = ?;`;
    db.query(sql, req.body.purchaser_id ,(err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取用户购买商品失败！');

        res.send({
            status: 0,
            mesage: "获取用户购买商品成功!",
            retdata: results
        })
    })
}

//查询所有商品
exports.getAllGoods = (req,res)=>{
    const sql =`select * from goods;`;
    db.query(sql, (err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取所有商品列表失败！');

        res.send({
            status: 0,
            mesage: "获取所有商品列表成功!",
            retdata: results
        })
    })
}
